package com.starxg.m3u8.gui;

import java.io.IOException;

import com.starxg.m3u8.exception.M3U8Exception;

import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.StageStyle;

/**
 * LoadingDialog
 * 
 * @author huangxingguang@lvmama.com
 * @date 2020-08-19 14:08
 */
public class LoadingDialog extends Dialog<Void> {
    private double xOffset = 0;
    private double yOffset = 0;
    private boolean isClose = false;

    public LoadingDialog() {
        this("提示");
    }

    public LoadingDialog(String title) {
        this(false, title);
    }

    public LoadingDialog(boolean isShowCancel, String title) {
        DialogPane dialogPane = getDialogPane();

        try {
            Pane root = FXMLLoader.load(getClass().getResource("/fxml/loading.fxml"));
            root.setPadding(Insets.EMPTY);
            dialogPane.setContent(root);
        } catch (IOException e) {
            throw new M3U8Exception(e);
        }

        HBox box = (HBox) dialogPane.lookup("#box");
        Label label = (Label) dialogPane.lookup("#title");
        label.setText(title);

        ProgressBar progressBar = (ProgressBar) dialogPane.lookup("#progressBar");
        Button btnCancel = (Button) dialogPane.lookup("#btnCancel");

        if (!isShowCancel) {
            box.getChildren().remove(btnCancel);
        }

        btnCancel.setOnAction(e -> close());

        initStyle(StageStyle.UNDECORATED);
        dialogPane.setStyle("-fx-border-color: #707070;");
        dialogPane.getButtonTypes().addAll(new ButtonType("关闭", ButtonBar.ButtonData.CANCEL_CLOSE));
        ButtonBar lookup = (ButtonBar) getDialogPane().lookup(".button-bar");
        dialogPane.getChildren().remove(lookup);
        dialogPane.setPadding(Insets.EMPTY);
        setResizable(true);
        drag(progressBar, dialogPane);

        setOnCloseRequest(e -> {
            if (!isClose) {
                e.consume();
            }
        });

    }

    private void drag(Node... nodes) {
        for (Node node : nodes) {
            node.setOnMousePressed(event -> {
                xOffset = event.getSceneX();
                yOffset = event.getSceneY();
            });
            node.setOnMouseDragged(event -> {
                setX(event.getScreenX() - xOffset);
                setY(event.getScreenY() - yOffset);
            });
        }
    }

    public void closeNow() {
        isClose = true;
        close();
    }

}
